<?php
/*
 * @Date: 2020-09-13 22:02:46
 * @名称: 用户 - 操作控制器 - 注册控制器
 * @版本: 0.01
 * @作者: 初雪桜
 * @邮箱: 202184199@qq.com
 * @最后编辑: 初雪桜
 * @LastEditTime: 2021-01-29 01:01:20
 * @FilePath: /Site/app/api/controller/User/Operation/UserReg.php
 */

namespace app\api\controller\User\Operation;

use app\BaseController;
use think\facade\Db;

class UserReg extends BaseController
{
    /**
     * 用户注册
     *
     * @param String $userName //@a 用户名
     * @param String $name //@a 昵称
     * @param String $passWord //@a 密码
     * @param String $gender //@a 性别
     * @return Map
     */
    public function UserReg($userName, $name, $passWord, $gender)
    {
        if ($gender < 0 || $gender > 2) { //0机器人 1男性 2 女性
            return errorJsonReturn('gender Error', '性别错误');
        }
        if ($userName == null) {
            return errorJsonReturn('User name or password cannot be empty');
        }
        if ($passWord == null) {
            return errorJsonReturn('User name or password cannot be empty');
        }
        $selectDb = Db::table('user_info')
            ->where(["user_name" => $userName])
            ->count();
        if ($selectDb) {
            return errorJsonReturn('repeat of user name', "用户名重复");
        }
        if (!preg_match('/^(?![^a-zA-Z]+$)(?!\D+$).{6,}$/', $passWord)) {
            return errorJsonReturn('Password must include alphanumeric', "密码必须包含数字字母");
        }
        if (!filter_var($userName, FILTER_VALIDATE_EMAIL)) {
            return errorJsonReturn('Please enter email', "请输入邮箱");
        }

        $userId = GenerateId();
        if (sendActivation($userName, $userId, $name)) {


            //@d 检查用户喜欢书籍表 有没有问题
            $bookLikeTableName = Db::table("book_like_controller") //定位到书籍喜欢表控制器
                ->order('id desc')
                ->find();
            if ($bookLikeTableName["user_count"] >= config("apiconfig.bookLikeDataBaseMaxCount")) {
                //! 判断当前表是不是到了满用户 满用户就创建新的表
                $LikeComicsTableName = "book_like_" . randIdStructure(99999, 32); //@x 表的随机名称
                $sql = "CREATE TABLE `$LikeComicsTableName` (
                    `id` int NOT NULL AUTO_INCREMENT,
                    `book_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '书籍id',
                    `user_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户id',
                    `like_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '喜欢id',
                    `like_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '喜欢时间',
                    PRIMARY KEY (`id`)
                  ) ENGINE=InnoDB AUTO_INCREMENT=111 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='用户漫画喜欢表';";
                Db::query($sql); //创建表
                Db::table("book_like_controller") //把创建的表的名称插入控制器
                    ->insert([
                        "table_name" => "$LikeComicsTableName",
                        "user_count" => 1
                    ]);
            } else {
                Db::table("book_like_controller") //当用户可以插入这张表则更新一下数据
                    ->where($bookLikeTableName)
                    ->inc('user_count')
                    ->update();
                $LikeComicsTableName = $bookLikeTableName["table_name"];
            }
            //@d 检查用户喜欢书籍表 有没有问题
            //@x 检查用户喜欢评论表
            $commentLikeTableName = Db::table("comment_like_controller") //定位到书籍喜欢表控制器
                ->order('id desc')
                ->find();
            if ($commentLikeTableName["user_count"] >= config("apiconfig.comicsLikeDataBaseMaxCount")) {
                //! 判断当前表是不是到了满用户 满用户就创建新的表
                $commentTableName = "comment_like_" . randIdStructure(99999, 32); //@x 表的随机名称
                $sql = "CREATE TABLE `$commentTableName` (
                    `id` int NOT NULL AUTO_INCREMENT,
                    `comment_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '评论id',
                    `comment_table_name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '喜欢的评论所在的表',
                    `user_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户id',
                    `like_id` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '喜欢id',
                    `like_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '喜欢时间',
                    PRIMARY KEY (`id`)
                  ) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='用户喜欢表 对应用户开头为0 的';";
                Db::query($sql); //创建表
                Db::table("comment_like_controller") //把创建的表的名称插入控制器
                    ->insert([
                        "table_name" => "$commentTableName",
                        "user_count" => 1
                    ]);
            } else {
                Db::table("comment_like_controller") //当用户可以插入这张表则更新一下数据
                    ->where($commentLikeTableName)
                    ->inc('user_count')
                    ->update();
                $commentTableName = $commentLikeTableName["table_name"];
            }
            //@x 检查用户喜欢评论表
            Db::Table('user_info')
                ->insert([
                    "user_name" =>  $userName, //'用户名'
                    "pass_word" =>   $passWord, //'密码'
                    "to_ken" =>  null, //'令牌'
                    "application_time" =>  date('Y-m-d H:i:s'), //'注册时间'
                    "characters" =>  "", //'不知道有啥用'
                    "role" =>  "member", //'角色'
                    "exp" =>  0, //'经验'
                    "slogan" =>  null, //'个性签名'
                    "verified" =>  0, //'认证用户 真假'
                    "_id" =>  $userId, //'随机生成的id'
                    // "title"=>   ,//'等级名称 类似于冒泡潜水之类的'
                    // "level" =>   0, //'等级'
                    "path" =>   null, //'头像路径'
                    "original_name" =>  null, //'头像名称'
                    "file_server" => config("globalsettings.Registered_user_image"), //'头像服务器地址'
                    "gender" =>  $gender, //'性别 0机器人 1男性 2 女性'
                    "name" =>  $name, //'昵称'
                    "character" =>  "", //'头像框url'
                    "exit_class_info" =>  0, //'用户是否允许修改分类信息'
                    "images_update" =>   0, //'是否允许上传图片'
                    "state" =>   0, //'用户状态 1 正常 0异常'
                    "exp_state" =>  2, //'异常原因 1封禁 2待认证'
                ]);
            Db::Table('user_info_table_name')
                ->insert([
                    "_id" =>  $userId, //'用户id'
                    "book_like_table_name" =>   $LikeComicsTableName, //'书籍喜欢表的名字'
                    "comment_like_table_name" =>  $commentTableName, //'评论喜欢表的名字'

                ]);
            echo '激活邮件已发送至您的邮箱';
        } else {
            echo '发件系统异常';
        }
        return;
    }
}
function GenerateId()
{
    $GenerateTableID = randIdStructure(0, 254);
    $idState = Db::table('user_info')
        ->where(["_id" => $GenerateTableID])
        ->count();
    if ($idState) {
        return GenerateId();
    } else {
        return $GenerateTableID;
    }
}
